import React, { Component } from 'react';
import './index.less';
import { base, promptBox, toast } from 'nc-lightapp-front';
import InfoSetting from './components/InfoSetting/index';
import { hrAjax as proFetch } from 'src/hrpub/common/utils/utils';

const {
    NCModal,
    NCButton,
    NCSelect
} = base;
const { NCOption } = NCSelect;
const {
    Header: NCHeader,
    Body: NCBody,
    Footer: NCFooter
} = NCModal;
let initTemp = false;
class SettingModal extends Component {
    constructor(props) {
        super(props);
        this.state = {
            // preSettingVisible: false,
            infoSettingVisible: false,
            preSettingTableDate: [],
            currentInfoSet: '', // 当前信息集
            dateFormatData: [], // 日期格式
            infoSetItemData: [], // 信息项
            getInfoNames: {},
            selectedInfoSet: '', // 选择的当前信息项
            editStatus: false,  // 是否为从修改进入的
            currentInfoItem: {},
            datecontrol: false, // 是否可以选择日期格式
            dateFormat: '', // 选择得日期格式
            prefixValue: '',  // 前缀
            suffixValue: '', // 后缀
            searchData: {},
            settingDisabled: true
        }
    }
    init = () => {
        if (!initTemp) {
            this.processTemplate()
            initTemp = true
        }
        this.getSetTableData()
    }
    processTemplate = () => {
        const { meta, json } = this.props;
        let template = meta.getMeta();
        let that = this;
        template['conditionList'].items.push({
            attrcode: 'opr',  // 
            itemtype: 'customer',
            hyperlinkflag: false,
            label: json["cm6011-000064"] || '操作',
            textAlign: 'center',
            visible: true,
            fixed: 'right',
            render(index, record) {
                return (
                    <div>
                        <span style={{ marginRight: '5px' }} onClick={() => that.editRow(index, record)} style={{ cursor: 'pointer', marginRight: '5px', color: '#0073E1' }}>{json["hi6007-000030"] || '修改'}</span>
                        <span onClick={() => that.deleteRow(index, record)} style={{ cursor: 'pointer', color: '#0073E1' }}>{json["hi6007-000031"] || '删除'}</span>
                    </div>
                )
            }
        });
        meta.setMeta(template);
    }

    // 新增
    addNew = async () => {
        this.setState({
            editStatus: false,
        }, () => {
            this.getTreeData()
        })
    }

    // 获取信息集和信息项
    getTreeData = (record) => {
        return proFetch({
            url: '/nccloud/hrpub/rptdef/AddInitAction.do',
            body: {
                pk_infoset: this.props.selectedRow.values['vmodeltype'].value, // 
            }
        })
            .then(async (res) => {
                if (res.success) {
                    if (res.data) {
                        this.setTreeData(res.data, record);
                    }
                }
            })
    };

    // 设置信息集和信息项
    setTreeData = async (data = {}, record = {}) => {
        // const {props, action} = this.comp;
        const { syncTree, json } = this.props;
        const { infoset = [], dateFormat } = data;

        const { treeData, getInfoNames, tableMap } = await this.formatTree(infoset);
        const children = treeData;
        let root = [{
            children,
            code: json["cm6011-000157"] || '信息集',
            id: null,
            isOrgStruSort: false,
            innercode: null,
            isleaf: false,
            key: 'root',
            name: json["cm6011-000157"] || '信息集',
            nodeData: {
                nodeValue: {}
            },
            pid: null,
            refname: json["cm6011-000157"] || '信息集',
            refpk: 'root',
            title: json["cm6011-000157"] || '信息集'
        }];
        this.setState({
            infoSettingVisible: true,
        })
        syncTree.setSyncTreeData('infoset', root);
        let selectKey, currentInfoItem = {}, editStatus = false;
        if (Object.keys(record).length === 0) {
            selectKey = children[0].refpk;
            editStatus = false;
        } else {
            // 修改
            selectKey = record.values.pk_infoset.value;
            currentInfoItem = { 
                key: record.values.pk_info_item.value, 
                name: record.values.fieldname.value.split('.')[1], 
                code: record.values.fieldcode.value,
                pid: record.values.pk_infoset.value 
            };
            syncTree.setNodeDisable('infoset', true);
            editStatus = true;
        }
        syncTree.setNodeSelected('infoset', selectKey);
        syncTree.openNodeByPk('infoset', 'root');
        // console.log(selectedInfoSet, getInfoNames[selectKey])
        this.setState({
            selectKey,
            // handleItem: children[0].nodeData.nodeValue
            dateFormatData: dateFormat,
            currentInfoItem,
            editStatus,
            selectedInfoSet: getInfoNames[selectKey],
            infoSetItemData: tableMap[selectKey],
        });
    };
    // 设置信息集和信息项格式
    formatTree = async (InfoSet = []) => {
        let tableMap = {}
        let getInfoNames = {}
        let treeData = InfoSet.map((item, index) => {
            if (!getInfoNames[item.key]) {
                getInfoNames[item.key] = item.name
            }
            if (item.children && item.children.length > 0) {
                if (!tableMap[item.key]) {
                    tableMap[item.key] = item.children

                }
                item.children = [];
                return item
            }
        })

        // let firstKey = treeData[0].key
        this.setState({
            allTree: InfoSet,
            treeData: treeData, //信息集树的数据
            tableMap: tableMap, //信息集表格的映射数据
            getInfoNames: getInfoNames,
        })
        return { treeData, getInfoNames, tableMap }
    };
    // 选择信息集
    onTreeSelect = (key) => {
        console.log(key)
        const { form } = this.props;
        if (key === 'root') return;
        let infoSetItemData = this.state.tableMap[key]
        let selectedInfoSet = this.state.getInfoNames[key]
        /*清空表单所有数据*/
        /*exceptArr array，不需要清空的字段数据 */
        form.EmptyAllFormValue('conditionCard');
        // form.setFormStatus('conditionCard', "browse");
        this.setState({
            infoSetItemData: infoSetItemData,
            selectKey: key,
            selectedInfoSet: selectedInfoSet,
            datecontrol: false,
            dateFormat: '', // 选择得日期格式
            prefixValue: '',  // 前缀
            suffixValue: '', // 后缀
            searchData: {},
            settingDisabled: true
        })
    }

    // 获取已经设置过得表格数据
    getSetTableData = () => {
        const {
            form,
            editTable,
            button,
            selectedRow
        } = this.props;

        return proFetch({
            url: '/nccloud/hrpub/rptdef/ListAction.do',
            body: {
                pk_infoset: selectedRow.values['vmodeltype'].value,// '1001Z710000000002YZJ',
                pk_conmodel: selectedRow.values['pk_conmodel'].value
            }
        })
            .then(async (res) => {
                if (res.success) {
                    if (res.data) {
                        editTable.setTableData('conditionList', { rows: res.data.data['conditionList'].rows });
                    } else {
                        editTable.setTableData('conditionList', { rows: [] });
                    }
                }
            }, (err) => {
                console.log(err.message)
            })

    }
    // 删除
    deleteRow = (index, record) => {
        const { json } = this.props;
        promptBox({
            color: 'warning',
            title: json["cm6011-000041"] || '确认删除', // 确认删除
            content: json["cm6011-000158"] || '是否确认要删除', // 是否确认要删除,
            beSureBtnClick: () => {
                return proFetch({
                    url: '/nccloud/hrpub/rptdef/DeleteAction.do',
                    body: {
                        id: record.values.id.value,
                    }
                })
                    .then(async (res) => {
                        if (res.success) {
                            toast({
                                color: 'success',
                                content: json["cm6011-000004"] || '删除成功'//
                            });
                            this.getSetTableData()
                        }
                    })
            }
        });
    }

    // 修改
    editRow = async (index, record) => {
        this.setState({
            editStatus: true,
            settingDisabled: false
        })
        await this.getTreeData(record)
        await this.toEditPage(record)
    }
    // 去编辑
    toEditPage = (record) => {
        const { form, selectedRow } = this.props;
        return proFetch({
            url: '/nccloud/hrpub/rptdef/QueryAction.do',
            body: {
                id: record.values.id.value,
                pk_conmodel: selectedRow.values['pk_conmodel'].value,
            }
        })
            .then(async (res) => {
                if (res.success) {
                    if (res.data) {
                        let formData = res.data.form.conditionCard
                        form.setAllFormValue({
                            'conditionCard': formData
                        });
                        /*设置表单编辑性*/
                        /*values Object,格式为{'attrcode': true/false}*/
                        // form.setFormItemsDisabled(formId, values)
                        // form.setFormStatus('conditionCard','edit')
                        this.setState({
                            datecontrol: res.data.datecontrol, // 是否可以选择日期格式
                            dateFormat: res.data.dateFormat || '', // 选择得日期格式
                            prefixValue: res.data.prefix,  // 前缀
                            suffixValue: res.data.suffix // 后缀
                        })
                    }
                }
            })
    }

    update = (payload) => {
        this.setState(payload)
    }

    onClose = () => {
        const {
            onClose,
            form,
            json
        } = this.props;

        promptBox({
            color: 'warning',
            title: json['cm6011-000000'], // 确认取消
            content: json['cm6011-000123'], // 是否确认要取消,
            beSureBtnClick: () => {
                form.EmptyAllFormValue('folder');
                onClose && onClose();
            }
        });
    }

    onChange = (v) => {
        console.log(v)

    }
    showButton = () => {
        const {
            json
        } = this.props;
        // let a = [{name: '合同1', key: '1'}, {name: '合同2', key: '2'}]
        return (
            <div className='button-add'>
                {/* <div style={{
                    float: 'left',
                    marginBottom: '5px'
                }}>
                    <NCSelect
                    value={'1'}
                    onChange={(v) => onChange(v)}
                    >
                        {
                            a.map((item) => {
                                return <NCOption key={item.key}>{item.name}</NCOption>
                            })
                        }
                    </NCSelect>
                </div> */}
                <div style={{
                    float: 'right',
                    marginBottom: '5px'
                }}>
                    <NCButton colors="primary" size="sm" onClick={this.addNew}>{json["cm6011-000159"] || '新增'}</NCButton>
                </div>
            </div>
        )
    }

    shouldComponentUpdate(nextProps, nextState) {
        if (!this.props.visible && !nextProps.visible) {
            return false
        }

        return true;
    }
    render() {
        const {
            visible,
            json,
            editTable,
            tableId
        } = this.props;

        return (
            <div>
                <NCModal
                    show={visible}
                    onHide={this.onClose}
                    backdrop={'static'}
                    size="lg"
                    dialogClassName="nc-modal-height"
                    onEntered={this.init}
                >
                    <NCHeader
                        closeButton={true}
                    >
                        {json["cm6011-000160"] || '条件预置'}
                    </NCHeader>
                    <NCBody>
                        {this.showButton()}
                        {/* table */}
                        {
                            editTable.createEditTable('conditionList', {
                                // cancelCustomRightMenu: true,
                                showIndex: true,        //显示序列号
                                // showCheck: true,        //显示复选框
                                height: 340
                            })
                        }
                    </NCBody>
                </NCModal>
                <InfoSetting
                    {...this.props}
                    {...this.state}
                    selectedRow={this.props.selectedRow}
                    json={json}
                    visible={this.state.infoSettingVisible}
                    update={this.update}
                    getSetTableData={this.getSetTableData}
                    onTreeSelect={this.onTreeSelect}
                />
            </div>
        );
    }
}

export default SettingModal;